/*select sku, qty 
from fg_st_ctrl 
where loca_code = 'KO' and qty < 0
order by sku
*/
begin tran

set nocount on
declare @sku nvarchar(20), @qty int, @qty_st int, @qty_chk int

select sku, qty 
from fg_st_ctrl 
where loca_code = 'KO' and qty < 0 
order by sku

select @qty_chk = sum(qty )
from fg_st_ctrl 
where loca_code = 'KO'

declare  cu cursor for 
select sku, qty 
from fg_st_ctrl 
where loca_code = 'KO' and qty < 0 
order by sku
open cu
fetch cu into @sku, @qty
while @@fetch_status = 0
begin
	declare cu2 cursor for 
	select qty 
	from fg_st_ctrl 
	where loca_code = 'KO' and qty > 0 and sku = @sku order by last_upd_date 
	open cu2
	fetch cu2 into @qty_st
	while @@fetch_status = 0
	begin
		if(@qty<0)
		begin
			if(@qty+@qty_st) > 0
			begin
				update fg_st_ctrl set qty = (qty + @qty)  where CURRENT OF cu2 
				update fg_st_ctrl set qty = 0  where CURRENT OF cu
				delete fg_st_ctrl where CURRENT OF cu
			end
			else
			begin
				update fg_st_ctrl set qty = 0  where CURRENT OF cu2
				delete fg_st_ctrl where CURRENT OF cu2
				update fg_st_ctrl set qty = qty + @qty_st  where CURRENT OF cu 
			end
			select @qty = @qty + @qty_st
		end
		
		fetch cu2 into @qty_st
	end
	close cu2
	deallocate cu2
fetch cu into @sku, @qty
end
close cu
deallocate cu
  
select sum(qty ) aa
from fg_st_ctrl 
where loca_code = 'KO'
 

select sum(qty )
from fg_st_ctrl 
where loca_code = 'KO'
having sum(qty) = @qty_chk


if @@rowcount = 0	
begin
	raiserror('update error',16,1)
	rollback tran
end
else
	commit tran


--set nocount off

